<?php
// 数据库处理模型
class Model{
public $error;
public $table;
 public $opt=array(
				   'filed'=>' * ',
				    'where'=>'',
				    'group'=>'',
				    'having'=>'',
				    'order'=>'',
				    'limit'=>'',
	);

// 构造函数
public function __construct($table=null){
    // 设置表名
    if($table)$this->table=$table;
    // 连接数据库
    if(!@mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'))){
    	die('数据库连接失败');
    }
   // 设置字符集
    mysql_query("SET NAMES ".C('DB_CHARSET'));
    if(!@mysql_select_db(C('DB_NAME'))){
    	die('数据库连接失败');
    }
}
 public function filed($a){
     $this->opt['filed']=$a;
     return $this;
 }
 public function where($a){
 	$this->opt['where']=" WHERE ".$a;
 	return $this;
 }
 public function group($a){
 	$this->opt['group']=" GROUP BY ".$a;
 	return $this;
 }
public function having($a){
	$this->opt['having']=" HAVING ".$a;
	return $this;

}
public function order($a){
	$this->opt['order']=" ORDER BY ".$a;
	return $this;
}
public function limit($a){
	$this->opt['limit']=" LIMIT ".$a;
	return $this;
}
public function find(){
		$data = $this->select();
		return $data?current($data):$data;
	}
// 查询数据
 function select(){
   $sql="SELECT {$this->opt['filed']} FROM ".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];
   // p($sql);p($this->query($sql));exit;
   return $this->query($sql);

}
// 删除数据（必须有条件)
//delete from table where cid=1;
function delete(){
	if(empty($this->opt['where']))return false;
  $sql="delete from ".$this->table.$this->opt['where'];
  // echo $sql;exit;
  return $this->exe($sql);

}
// 更新数据
function update($data){
	if(empty($this->opt['where']))return false;
	//UPDATE CLASS set cname='xx'
	$sql="UPDATE ".$this->table." SET ";
	// p($sql);exit;
	foreach ($data as $name=>$value) {
      $sql.=$name. "='$value',";
	}
	$sql=substr($sql, 0,-1).$this->opt['where'];
	return $this->exe($sql);
}
// 插入数据
function insert($data){
   $sql="INSERT INTO ".$this->table;
   $filed=array_keys($data);
   $value=array_values($data);
   $sql.="(".implode(',', $filed).") VALUES('".implode("','", $value)."')";
  // p($sql);exit;
   return $this->exe($sql);
}

// 查询结果集
function query($sql){
	 $result=mysql_query($sql);
	 if($result){
	 	$rows=array();
	 	while ($row=mysql_fetch_assoc($result)) {
	 		$rows[]=$row;	
	 	}
	 	return $rows;
	 }else{

	 	die(mysql_error());
	 }
}

function exe($sql){
	$status=mysql_query($sql);
	if($status){
		$insertId=mysql_insert_id();
		return $insertId?$insertId:true;
	}else{
		die(mysql_error());
	}
}
function getAffectedRow(){
	return mysql_affected_rows();
}

}



?>